import {Object3D,Vector2} from 'three';
import Mix from '../../general/mix';
import Constant from './ui-constant';
import UIBox from './ui-box';
import UIMesh from './ui-mesh';
import UIMaterial from './ui-material';
import UIInlineManager from './ui-inline-manager';
import UIFrame from './ui-frame';

export default class UIBlock extends Mix(Object3D)(UIBox,UIInlineManager,UIMaterial,UIMesh){
    constructor(options={}){
        super(options);
        this.isBlock=true;
        this.size = new Vector2(1,1);
        this.tSize = new Vector2( 1, 1 );
        this.frame = new UIFrame( this.getBackgroundMaterial() );
        this.frame.onBeforeRender = () => {
            if ( this.updateClippingPlanes ) {
                this.updateClippingPlanes();
            }
        };
        this.add( this.frame );
        this.set( options );
    }

    get uiType(){
        return Constant.TYPE_BLOCK;
    }

    parseParams() {
        const bestFit = this.getBestFit();
        if ( bestFit !==Constant.VALUE_NONE && ( this.children.find( child => child.isText ))) {
            this.calculateBestFit(bestFit);
        }
        else {
            this.children.filter(child => {return child.isText}).forEach(child => {
                child._fitFontSize = undefined;
            });
        }
    }
    updateLayout() {
        const WIDTH = this.getWidth();
        const HEIGHT = this.getHeight();
        if ( !WIDTH || !HEIGHT ) {
            console.warn( 'Block got no dimension from its parameters or from children parameters' );
            return;
        }
        this.size.set( WIDTH, HEIGHT );
        this.frame.scale.set( WIDTH, HEIGHT, 1 );
        if ( this.frame ) this.updateBackgroundMaterial();
        this.frame.renderOrder = this.getParentsNumber();
        if ( this.autoLayout ) {
            this.setPosFromParentRecords();
        }
        if ( this.children.find( child => child.isInline ) ) {
            this.computeInlinesPosition();
        }
        this.computeChildrenPosition();
        if ( this.getUIParent() ) {
            this.position.z = this.getOffset();
        }
    }
    updateInner() {
        if ( this.getUIParent() ) {
            this.position.z = this.getOffset();
        }
        if ( this.frame ) this.updateBackgroundMaterial();
    }

} 